package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.StackProblem;
import cn.pugle.oj.catalog.TreeProblem;

/**
 * 235 236
 * 非bst
 *
 * <p>
 * 其实树中没有重复元素, 所以可以优化, 不用返回两个boolean
 * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/solution/
 *
 * <p>
 * 还有个用栈的方法也不错
 * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/65236/JavaPython-iterative-solution
 *
 * Tarjan算法
 * https://segmentfault.com/a/1190000015145319?utm_source=index-hottest
 *
 * @author tzp
 * @since 2020/9/16
 */
public class LC236 implements TreeProblem, StackProblem {

    public static class Pair<A, B> {
        public A a;
        public B b;

        public Pair(A a, B b) {
            this.a = a;
            this.b = b;
        }
    }

    TreeNode lca = null;

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return null;
        rec(root, p, q);
        return lca;
    }

    //后序遍历
    public Pair<Boolean, Boolean> rec(TreeNode root, TreeNode p, TreeNode q) {
        boolean hasP = false, hasQ = false;
        if (root.val == p.val) hasP = true;
        if (root.val == q.val) hasQ = true;
        if (root.left != null) {
            Pair<Boolean, Boolean> resultLeft = rec(root.left, p, q);
            if (resultLeft.a) hasP = true;
            if (resultLeft.b) hasQ = true;
        }
        if (root.right != null) {
            Pair<Boolean, Boolean> resultRight = rec(root.right, p, q);
            if (resultRight.a) hasP = true;
            if (resultRight.b) hasQ = true;
        }
        if (hasP && hasQ && lca == null) {
            lca = root;
        }
        return new Pair<>(hasP, hasQ);
    }

    public static void main(String[] args) {
        Integer[] a = {1, 2, 4, 3, 5, 7, 10, 6, null, 8, null, 11, 9, 15, null, null, null, 12, null, null, null, 13, null, null, null, null, 14};
        TreeNode treeNode = TreeNode.arrayToTreeNode(a);
        System.out.println(new LC236().lowestCommonAncestor(treeNode,
                new TreeNode(15), new TreeNode(6)));
    }
}
